package com.pig4cloud.pig.ads.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dy.yunying.api.entity.WanGameDO;
import com.google.api.client.util.Lists;
import com.pig4cloud.pig.admin.api.entity.SysUser;
import com.pig4cloud.pig.admin.api.feign.RemoteUserService;
import com.pig4cloud.pig.ads.service.SelfCustomAudienceService;
import com.pig4cloud.pig.ads.service.AdvService;
import com.pig4cloud.pig.api.dto.FreeCrowdPackDto;
import com.pig4cloud.pig.api.vo.FreeCrowdPackVo;
import com.pig4cloud.pig.api.vo.FreeCrowdVo;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.api.dto.SelfCustomAudienceDTO;
import com.pig4cloud.pig.api.dto.SelfCustomAudiencePushDTO;
import com.pig4cloud.pig.api.entity.SelfCustomAudience;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.security.annotation.Inner;
import io.swagger.annotations.Api;
import lombok.Cleanup;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/selfCustomAudience")
@Api(value = "selfCustomAudience", tags = "自有人群包模块")
//@Inner(value = false)
public class SelfCustomAudienceController {

	private final SelfCustomAudienceService selfCustomAudienceService;

	private final AdvService advService;
	private final RemoteUserService remoteUserService;


	/**
	 * fegin 调用 功运营服务打包使用
	 * @param entity
	 * @return
	 */
	@Inner
	@PostMapping("/getListByDto")
	public List<SelfCustomAudience> getListByDto(@RequestBody SelfCustomAudience entity){
		if (StringUtils.isBlank(entity.getName())) {
			return Lists.newArrayList();
		}
		List<SelfCustomAudience> list = selfCustomAudienceService.list(Wrappers.<SelfCustomAudience>query()
				.lambda().eq(SelfCustomAudience::getName, entity.getName()).eq(SelfCustomAudience::getIsDeleted,0));
		return list;
	}

	/**
	 * fegin 调用 功运营服务打包使用
	 * @param entity
	 * @return
	 */
	@Inner
	@PostMapping("/saveEntity")
	public boolean saveEntity(@RequestBody SelfCustomAudience entity){
		if (StringUtils.isBlank(entity.getName())
			|| StringUtils.isBlank(entity.getDownloadUrl())
			|| entity.getType()==null) {
			return false;
		}
		return selfCustomAudienceService.save(entity);
	}



	/**
	 * 已迁移至动心查询 AudiencePackController.page
	 * 自由人群包列表
	 *
	 * @param page
	 * @param dto
	 * @return
	 */
	@SysLog("自由人群包列表")
	@PostMapping(value = "list")
	public R getFreeCrowdPackList(Page page, @RequestBody FreeCrowdPackDto dto) {
//		IPage<FreeCrowdVo> pageResult = selfCustomAudienceService.getFreeCrowdPackList(page, dto);
		return selfCustomAudienceService.getFreeCrowdList(dto);
	}

	/**
	 * 已迁移至动心查询 AudiencePackController.pack
	 * 自有人群打包
	 */
	@SysLog("自有人群打包")
	@PostMapping("/pack")
	public R createPackage(@RequestBody FreeCrowdPackDto dto) {
		if (dto.getType() == null) {
			return R.failed("打包字段不能为空");
		}
		if (StringUtils.isBlank(dto.getPackageName())) {
			return R.failed("人群包名称不能为空");
		}
		// 人群包名称不能重复
		List<SelfCustomAudience> list = selfCustomAudienceService.list(Wrappers.<SelfCustomAudience>query()
				.lambda().eq(SelfCustomAudience::getName, dto.getPackageName()));

		if (ObjectUtils.isNotEmpty(list)) {
			return R.failed("存在相同人群包名称");
		}
		// 不重复 才能打包
		R result = selfCustomAudienceService.downloadFreeCrowdPack(dto);
		return result;
	}


	/**
	 * 分页查询自有人群包信息
	 * 自有人群包不要权限，均能看到所有的数据
	 *
	 * @param page 分页对象
	 * @return 分页对象
	 */
	@SysLog("分页查询自有人群包信息")
	@GetMapping(value = "page")
	public R getSelfAudienceList(Page page, SelfCustomAudienceDTO dto) {

		//Integer id = SecurityUtils.getUser().getId();

		LambdaQueryWrapper<SelfCustomAudience> query = new LambdaQueryWrapper<>();
		query.and(wrapper -> wrapper.eq(SelfCustomAudience::getIsDeleted, 0));
		//创建时间
		query.apply(StringUtils.isNotBlank(dto.getStartDate()),
				"date_format (create_time,'%Y-%m-%d') >= date_format('" + dto.getStartDate() + "','%Y-%m-%d')");
		query.apply(StringUtils.isNotBlank(dto.getEndDate()),
				"date_format (create_time,'%Y-%m-%d') <= date_format('" + dto.getEndDate() + "','%Y-%m-%d')");
		//人群名称
		query.and(StringUtils.isNotBlank(dto.getName()), wrapper -> wrapper.like(SelfCustomAudience::getName, dto.getName()));

		//根据创建时间倒序
		query.orderByDesc(SelfCustomAudience::getCreateTime);

		IPage<SelfCustomAudience> listPage = selfCustomAudienceService.page(page, query);
		List<SelfCustomAudience> list = listPage.getRecords();
		if (!CollectionUtils.isEmpty(list)) {
			//获取当前操作用户ID集合
			List<Long> userIds = list.stream().map(SelfCustomAudience::getCreateId).filter(Objects::nonNull).collect(Collectors.toList());
			List<Integer> ids = userIds.stream().distinct().map(v -> v.intValue()).collect(Collectors.toList());
			R<List<SysUser>> userList = remoteUserService.getUserListByUserIds(SecurityConstants.FROM_IN, ids);
			if (userList != null && !CollectionUtils.isEmpty(userList.getData())) {
				//Map<用户ID,用户名称>
				Map<Integer, String> userMap = userList.getData().stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getRealName));
				list.forEach((item) -> {
					if (!CollectionUtils.isEmpty(userMap) && item.getCreateId() != null) {
						item.setCreateName(userMap.get(item.getCreateId().intValue()));
					}
				});
			}
		}
		return R.ok(listPage);
	}


	@SysLog("推送自有人群包")
	@PostMapping(value = "push")
	public R getSelfAudienceList(@RequestBody SelfCustomAudiencePushDTO dto) {
		if (CollectionUtils.isEmpty(dto.getIds())) {
			return R.failed("缺失必填参数ID");
		}
		if (dto.getMediaType() == null) {
			return R.failed("缺失必填参数媒体");
		}
		if (CollectionUtils.isEmpty(dto.getAdvertiserIds())) {
			return R.failed("缺失必填参数广告账户");
		}
		return selfCustomAudienceService.push(dto);
	}

	@SneakyThrows
	@SysLog("下载自有人群包")
	@GetMapping(value = "downLoad")
	public void downLoad(HttpServletRequest request, HttpServletResponse response, @RequestParam Long id) {

		SelfCustomAudience selfCustomAudience = selfCustomAudienceService.getById(id);
		if (selfCustomAudience != null) {
			OutputStream ops = null;
			URL url = new URL(selfCustomAudience.getDownloadUrl());
			String fileName = selfCustomAudience.getDownloadUrl().substring(selfCustomAudience.getDownloadUrl().lastIndexOf("/") + 1);
			response.setCharacterEncoding("UTF-8");
			response.setHeader("Content-Type", "application/octet-stream");
			response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
			@Cleanup InputStream is = url.openStream();
			@Cleanup InputStreamReader isr = new InputStreamReader(is, "UTF-8");
			@Cleanup BufferedReader br = new BufferedReader(isr);
			String newLine = System.getProperty("line.separator");
			ops = response.getOutputStream();
			String lineTxt = null;
			while ((lineTxt = br.readLine()) != null) {
				ops.write(lineTxt.getBytes("UTF-8"));
				ops.write(newLine.getBytes());
			}
		}
	}


}
